from datetime import datetime, timedelta
from app import create_app, db
from app.models import User, Post

def insert_data():
    # 创建用户
    u1 = User(username='john', email='john@example.com')
    u2 = User(username='susan', email='susan@example.com')
    u3 = User(username='mary', email='mary@example.com')
    u4 = User(username='david', email='david@example.com')
    db.session.add_all([u1, u2, u3, u4])

    # 提交用户到数据库
    db.session.commit()

    # 创建帖子
    now = datetime.utcnow()
    p1 = Post(body="post from john", author=u1, timestamp=now + timedelta(seconds=1))
    p2 = Post(body="post from susan", author=u2, timestamp=now + timedelta(seconds=4))
    p3 = Post(body="post from mary", author=u3, timestamp=now + timedelta(seconds=3))
    p4 = Post(body="post from david", author=u4, timestamp=now + timedelta(seconds=2))
    db.session.add_all([p1, p2, p3, p4])

    # 提交帖子到数据库
    db.session.commit()

    # 设置关注关系
    u1.follow(u2)  # john follows susan
    u1.follow(u4)  # john follows david
    u2.follow(u3)  # susan follows mary
    u3.follow(u4)  # mary follows david
    db.session.commit()

if __name__ == '__main__':
    app = create_app()
    with app.app_context():
        insert_data()
